
<div class="layui-card layadmin-header">
  <div class="layui-breadcrumb" lay-filter="breadcrumb">
    <a lay-href="">主页</a>
    <a><cite>商户管理</cite></a>
    <a><cite>商户列表</cite></a>
  </div>
</div>

<div class="layui-fluid">
  <div class="layui-card">
    <div class="layui-tab layui-tab-brief">
      <ul class="layui-tab-title">
        <li class="layui-this">商户列表</li>
      </ul>
      <div class="layui-tab-content">
        <div class="layui-tab-item layui-show">
          <div class="layui-row">
            <div class="layui-form" style="float:right;">
              <div class="layui-form-item" style="margin:0;">
                <div class="layui-input-inline">
                  <input type="text" name="mchId" id="searchMchId" placeholder="商户ID" autocomplete="off" class="layui-input">
                </div>
                <a id="search" class="layui-btn" data-type="reload"><i class="layui-icon layui-icon-search"></i>搜索</a>
              </div>
            </div>
          </div>
          <div class="layui-row">
            <div class="layuiAdmin-btns" style="margin-bottom: 10px;">
              <a class="layui-btn mchAddBtn"><i class="layui-icon layui-icon-add-1"></i>新增</a>
              <a class="layui-btn" id="passageBatch"><i class='layui-icon layui-icon-template-1'></i>通道统一配置</a>
              <a class="layui-btn layui-btn-danger" data-type="del" data-events="del" id="del"><i class="layui-icon layui-icon-delete"></i>彻底删除</a>
          </div>
        </div>
        <table id="XxPay_Mgr_Merchant_dataAll" lay-filter="XxPay_Mgr_Merchant_dataAll"></table>
        <div class='layui-row layui-fluid'>
            汇总统计： 总可用余额 <span style='color:red' id='totalBalacne' ></span> 元，
            总可用代付余额 <span style='color:red' id='totalAgentpayBalacne' ></span> 元。
          </div>
        </div>

      </div>
    </div>
  </div>
</div>

<script>
  layui.use(['admin', 'table', 'util'], function(){
    var $ = layui.$
            ,admin = layui.admin
            ,table = layui.table
            ,element = layui.element
            ,form = layui.form
            ,view = layui.view;

    element.render('breadcrumb', 'breadcrumb');

    $("#passageBatch").off().on("click", function(){
      var mchIds = [];
      var errorMsg = "";
      $.each(table.cache.tableReload, function(){
        var thisObject = $(".layui-table tr[data-index='"+this.LAY_TABLE_INDEX+"'] input[name='layTableCheckbox']");
        if(thisObject.is(':checked')){ //勾选状态

          if(this.type == 2){ //私有商户
            errorMsg = "私有商户不支持通道设置，请选择平台商户！";
            return false;
          }

          mchIds.push(this.mchId);
        }

      });
      if(errorMsg) return layer.alert(errorMsg);
      if(mchIds.length <= 0) return layer.alert("请勾选需要配置通道的商户！");
      if(mchIds.length > 10) return layer.alert("批量配置商户通道个数不得大于10个！");

      location.href = layui.setter.baseLocal + "merchant/pay_passage/batch_list/mchIds=" + mchIds;
    });

    $.setCountResult = function() {
        admin.req({
            type: 'get',
            url: layui.setter.baseUrl + '/account/mchCount',
            data: {},
            error: function(err){
                layer.alert(JSON.stringify(err.field), {
                    title: '错误提示'
                })
            },
            success: function(res){
                if(res.code == 0){
                    $('#totalBalacne').html((res.data.settAmountCount - res.data.unBalanceCount - res.data.frozenMoneyCount)/100.00);
                    $('#totalAgentpayBalacne').html((res.data.agentpayBalanceCount-res.data.unAgentpayBalanceCount-res.data.agentpayFrozenMoney)/100.00);
                }
            }
        });
    };

    //可用余额
    var tplBalance = function(d){
        var tipClass = 'mchBalanceTip_' + d.mchId;
        var tipStr = '账户余额：'+(d.balance)/100+'元<br/>账户不可用余额：'+(d.unBalance)/100+'元<br/>冻结金额：' + (d.frozenMoney)/100+'元';

        return "<span style='color: red'>"+d.availableBalance/100+"元</span><span tipStr='"+tipStr+"' tipClass='"+tipClass+"' class='mchBalanceTip "+tipClass+" layui-icon layui-icon-about'></span>";
    };
    //可用余额感叹号点击事件
    $('body').off('click', '.mchBalanceTip').on('click', '.mchBalanceTip', function(){
      layer.tips($(this).attr('tipStr'), '.'+$(this).attr('tipClass'), {
        tips: [1, '#3595CC'],
        time: 3000
      });
    });

    //可用代付余额
    var tplAgentpayBalance = function(d){
        var tipClass = 'mchAgentpayBalanceTip_' + d.mchId;
        var tipStr = '代付余额：'+(d.agentpayBalance)/100+'元<br/>代付不可用余额：'+(d.unAgentpayBalance)/100+'元' + '<br/>代付冻结金额：' + (d.agentpayFrozenMoney)/100 + '元';

        return "<span style='color: red'>"+d.agentpayBalance/100+"元</span><span tipStr='"+tipStr+"' tipClass='"+tipClass+"' class='mchAgentpayBalanceTip "+tipClass+" layui-icon layui-icon-about'></span>";
    };
    //可用代付余额感叹号点击事件
    $('body').off('click', '.mchAgentpayBalanceTip').on('click', '.mchAgentpayBalanceTip', function(){
        layer.tips($(this).attr('tipStr'), '.'+$(this).attr('tipClass'), {
            tips: [1, '#3595CC'],
            time: 3000
        });
    });

    var tplStatus = function(d){

        var checkedHtml = " mchId='"+d.mchId+"' ";
        if(d.status == 1) {
            checkedHtml += " checked";
        }
        return '<input type="checkbox" lay-filter="statusSwitch" lay-skin="switch" '+checkedHtml+' lay-text="启用|停用">';
    };

    var tplEdit = function(d){

        //私有商户 按钮
        var priBtn = "<a class='layui-btn layui-btn-primary layui-btn-xs' lay-event='setPrivateMchProduct'><i class='layui-icon layui-icon-util'></i>产品</a>"
          + "<a class='layui-btn layui-btn-primary layui-btn-xs' lay-event='setPrivateMchIfType'><i class='layui-icon layui-icon-engine'></i>接口</a>";

        //平台商户 按钮
        var platBrn = "<a class='layui-btn layui-btn-primary layui-btn-xs' lay-event='settConfig'><i class='layui-icon layui-icon-set-fill'></i>结算</a>" +
            "<a class='layui-btn layui-btn-primary layui-btn-xs' lay-event='payPassage'><i class='layui-icon layui-icon-template-1'></i>支付</a>" +
            "<a class='layui-btn layui-btn-primary layui-btn-xs' lay-event='agentpayPassage'><i class='layui-icon layui-icon-template'></i>代付</a>";

      return "<a class='layui-btn layui-btn-primary layui-btn-xs' target='_blank' lay-event='loginMerchant'><i class='layui-icon layui-icon-auz'></i>登录</a>" +
              "<a class='layui-btn layui-btn-primary layui-btn-xs' lay-event='merchantDetail'><i class='layui-icon layui-icon-about'></i>查看</a>" +
              ( d.type == 1 ? platBrn : priBtn ) +
              "<a class='layui-btn layui-btn-primary layui-btn-xs' lay-event='change'><i class='layui-icon layui-icon-rmb'></i>调额</a>" +
              "<a class='layui-btn layui-btn-primary layui-btn-xs' lay-event='agentpayRecharge'><i class='layui-icon layui-icon-rmb'></i>代充</a>" +
              /*"<a class='layui-btn layui-btn-primary layui-btn-xs' lay-event='pwdReset'>重置密码</a>" +*/
              "<a class='layui-btn layui-btn-xs' lay-event='edit'><i class='layui-icon layui-icon-edit'></i>编辑</a>";
    };

    // var tplAmount = function(d){
    //     return "<span style='color: darkgreen'>" + d.balance/100 + "</span>";
    // };

    //商户列表
    table.render({
      elem: '#XxPay_Mgr_Merchant_dataAll'
      ,url: layui.setter.baseUrl + '/mch_info/list' //列表接口
      ,where: {
          access_token: layui.data(layui.setter.tableName).access_token
      }
      ,id: 'tableReload'
      ,page: true
      ,cols: [[
        {type: 'checkbox', fixed: 'left'}
        ,{field: 'mchId', title: '商户ID'}
        ,{field: 'name', title: '商户名称'}
        ,{field: 'balance', title: '可用余额', templet: tplBalance}
        ,{field: 'agentPatBalance', title: '可用代付余额', templet: tplAgentpayBalance}
        /*,{title: '商户类型', templet: "<div>{{d.type == 1 ? '平台商户' : '私有商户'}}</div>"}*/
        ,{field: 'agentId', title: '代理商ID'}
        ,{field: 'status', title: '状态', templet: tplStatus}
        /*,{field: 'createTime', title: '时间', width: 200, templet: '<div>{{ layui.util.toDateString(d.createTime, "yyyy-MM-dd HH:mm:ss") }}</div>'}*/
        ,{field: 'edit', title: '操作', width: 650, fixed: 'right', templet: tplEdit }
      ]]
        ,skin: 'line'
        ,done: function () {
            // 初始化统计结果
            $.setCountResult();
        }
    });

    //监听工具条
    table.on('tool(XxPay_Mgr_Merchant_dataAll)', function(obj){
      var data = obj.data;
      if(obj.event === 'merchantDetail'){

          view.xxpayPopup("查看商户信息", "merchant/list/mch_view", {mchId: data.mchId}, {btn:false});

      } else if(obj.event === 'accountDetail'){
        location.href = layui.setter.baseLocal + "merchant/list/account_view/mchId=" + data.mchId;
      } else if(obj.event === 'payPassage'){
        if(data.type == 2) {
          layer.msg('私有账户,无需设置!');
          return;
        }
        location.href = layui.setter.baseLocal + "merchant/pay_passage/list/mchId=" + data.mchId;
      } else if(obj.event === 'agentpayPassage'){
        if(data.type == 2) {
          layer.msg('私有账户,无需设置!');
          return;
        }
        location.href = layui.setter.baseLocal + "merchant/agentpay_passage/list/mchId=" + data.mchId;
      } else if(obj.event === 'settConfig'){
        if(data.type == 2) {
            return layer.msg('私有账户,无需设置!');
        }

        view.xxpayPopup("商户结算设置", "merchant/list/mch_sett", {mchId: data.mchId}, {area:['70%','70%']});

      }else if(obj.event === 'pwdReset'){
        layer.prompt({
          formType: 1,
          title: '请输入新密码'
        }, function(value, index, elem){
          admin.req({
            type: 'get',
            url: layui.setter.baseUrl + '/mch_info/pwd_reset',
            data: {
              mchId : data.mchId,
              password : value
            },
            error: function(err){
              layer.alert(JSON.stringify(err.field), {
                title: '错误提示'
              })
            },
            success: function(res){
              if(res.code == 0){
                layer.msg('修改成功', {icon: 1});
              }
            }
          });
          layer.close(index);
        });
      }else if(obj.event === 'change'){

          view.xxpayPopup("商户余额变更", "merchant/list/mch_change", {mchId: data.mchId}, {btn: false, area:['40%','80%']});

      }else if(obj.event === 'edit'){

          view.xxpayPopup("编辑商户", "merchant/list/mch_edit", {mchId: data.mchId});

      }else if(obj.event === 'loginMerchant'){
        admin.req({
            type: 'post',
            url: layui.setter.baseUrl + '/mch_info/genLoginUrl',
            data: {mchId : data.mchId},
            success: function(resData){
                layer.alert("请点击登录按钮（有效期1分钟）：", {btn:['登录']}
                    ,function(aid){
                        window.open(resData.data.loginUrl);
                        layer.close(aid);
                    });
            }
        });
      }else if(obj.event === 'setPrivateMchProduct'){
          view.xxpayPopup("产品设置", "merchant/list/private_product", {mchId: data.mchId}, {btn:['确认保存']});
      }else if(obj.event === 'setPrivateMchIfType'){
          view.xxpayPopup("接口设置", "merchant/list/private_if_type", {mchId: data.mchId}, {btn:['确认保存']});
      }else if(obj.event === 'agentpayRecharge'){
          view.xxpayPopup("代付充值", "merchant/list/mch_agentpay_recharge", {mchId: data.mchId}, {btn: false, area:['40%','70%']});
      }

    });

      // 事件处理
      var events = {
          del: function () { //获取选中数据
              var checkedData = table.checkStatus("tableReload").data; //获得选中的数据
              if(checkedData.length === 0) return layer.msg('请选择数据');
              var delIds = [];
              $.each(checkedData, function(){
                  delIds.push(this.mchId);
              });

              //弹层
              var relationDeleteHtml = `
                <div style="color:red; margin:20px; padding-left:50px" >
                    <label class="layui-inline"> 此操作将删除选中数据及所有关联数据！是否继续删除？</label><br/><br/>
                    <label class="layui-inline"> 关联表：[商户信息表];[商户账户表];[商户支付通道表];[商户应用表];</label><br/>
                    <label class="layui-inline"> [代付通道表];[商户银行账号表];[商户统一扫码配置];[资金流水];</label><br/>
                    <label class="layui-inline"> [商户每日结算汇总];[批量结算明细表];[商户对账单];[结算记录表];</label><br/>
                    <label class="layui-inline"> [退款订单表];[商户通知表];[支付订单表];[转账订单表];[商户交易表];</label><br/>
                    <label class="layui-inline"> [代付记录表]</label>
                </div>
                <form class="layui-form center">
                    <div class="layui-form-item" style="margin-top:20px">
                        <label class="layui-form-label" style="width:130px;">平台超级密码：</label>
                        <div class="layui-input-inline" style="width: 312px;">
                            <input type="password" autocomplete="off" class="layui-input relationDeletePassword">
                        </div>
                    </div>
                    <div class="layui-form-item" style="margin-top:30px">
                        <div class="layui-input-block" style="margin-left: 180px;">
                            <button type="button" class="layui-btn layui-btn-danger relationDeleteBtn">确认删除</button>
                            <button type="button" class="layui-btn layui-btn-normal" onclick="layer.closeAll();">取消</button>
                        </div>
                    </div>
                </form>
            `;
              //打开弹层
              var thisLayerId = layer.open({ type: 1, area: ['520px', 'auto'], title: '提示', content: relationDeleteHtml });
              $(".relationDeleteBtn").click(function(){
                  var relationDeletePassword = $('.relationDeletePassword').val();
                  if(!relationDeletePassword) return layer.msg('请输入平台超级密码！');

                  var layerMsgId = layer.msg('正在执行删除任务... ',{time: 0, shade: 0.3});
                  admin.req({
                      type: 'get',
                      url: layui.setter.baseUrl + '/mch_info/relationDelete',
                      data: {ids: JSON.stringify(delIds), superPassword: relationDeletePassword},
                      error: function (err) {
                          layer.close(layerMsgId);
                          layer.alert(err);
                      },
                      success: function (res) {
                          layer.close(layerMsgId);
                          if(res.code == '0'){ //成功创建任务
                              layer.close(thisLayerId);
                              table.reload('tableReload');  //刷新页面
                              layer.alert("操作成功, 共删除了 "+res.data+" 条关联数据！");
                          }
                      },
                      complete: function(){
                          layer.close(layerMsgId);
                      }
                  });
              });
          }

      };

      form.on('switch(statusSwitch)', function(data){

          var mchId = $(data.elem).attr('mchId');
          var updateState = data.elem.checked ? "1" : "0";
          var loadingIndex = layer.load();
          admin.req({
              type: "POST",
              url: layui.setter.baseUrl + '/mch_info/updateStatus',
              data: {mchId: mchId, status: updateState},
              success: function(res){
                  if(res.code == 0) {
                      table.reload('tableReload');
                  }
              },
              complete:function(){
                  layer.close(loadingIndex);
              }
          });
      });

      $('.layuiAdmin-btns .layui-btn').on('click', function(){
          var othis = $(this)
              ,thisEvent = othis.data('events')
              ,type = othis.data('type');
          events[thisEvent] && events[thisEvent].call(this, othis, type);
      });


    // 搜索
    var $ = layui.$, active = {
      reload: function(){
        var mchId = $('#searchMchId').val();
        //执行重载
        table.reload('tableReload', {
          page: {
            curr: 1 //重新从第 1 页开始
          }
          ,where: {
            mchId: mchId
          }
        });
      }
    };
    $('#search').on('click', function() {
      var type = $(this).data('type');
      active[type] ? active[type].call(this) : '';
    });

    $('.mchAddBtn').click(function(){
        view.xxpayPopup("新增商户", "merchant/list/mch_add");
    });


    // 渲染表单
    form.render();
  });
</script>
